// 请求地址
const baseURL = "https://xf.xiaoyiyunwang.com/prod-api"
// const baseURL = "http://192.168.1.9:8080" // 诺
// const baseURL = "http://192.168.1.14:8080" //向
// token处理方法
import { getToken, removeToken } from '@/utils/auth.js'
// 请求封装
const request = (url : string, method : 'GET' | 'POST' | 'PUT' | 'DELETE', data : any = {}, headers : any = {}) => {
	// 从本地存储中获取token
	const token = getToken()
	// 设置token请求头
	headers['Authorization'] = `Bearer ${token}`
	// 设置默认请求头
	headers['Content-Type'] = 'application/json'

	return new Promise((resolve, reject) => {
		uni.request({
			// 拼接请求路径
			url: baseURL + url,
			// 请求类型
			method,
			// 请求参数
			data,
			// 请求头
			header: headers,
			// 超时时间
			timeout: 500000,
			success: (res) => {
				if (res.data.code == '200') {
					resolve(res.data)
				} else if (res.data.code == '401' || !token) {
					uni.showToast({
						title: '未授权,请重新登陆',
						icon: 'error',
						duration: 3000
					})
					// 返回登陆页
					uni.redirectTo({
						url: '/pages/login/login'
					})
					// 清除token
					removeToken()
					reject(res)
				} else {
					uni.showToast({
						title: res.data.msg,
						icon: 'error',
						duration: 3000
					})
					reject(res)
				}
			},
			fail: (error) => {
				uni.showToast({
					title: "请求失败，请检查网络",
					icon: 'none'
				})
				reject(error)
			}
		})


	})
}

// GET
export const getRequest = (url : string, params = {}, headers = {}) => {
	return request(url, 'GET', params, headers)
}

// POST
export const postRequest = (url : string, data = {}, headers = {}) => {
	return request(url, 'POST', data, headers);
};

// PUT
export const putRequest = (url : string, data = {}, headers = {}) => {
	return request(url, 'PUT', data, headers);
};